﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.IO.Ports;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using MasterDatabase;

namespace Job_Assignment
{
    public partial class Form1 : SQL_APPL
    {
        TimeSpan Run_Time = TimeSpan.Parse("00:00:00");
        void ProductionPlanDetail_Create_BT_Click(object sender, EventArgs e)
        {
            string sql_cmd, mess, cell_str;
            bool b;
            int count, qty, temp_qty;
            string po, part, part_name;
            string line_id, line_name, subline, subline_name, wst, wst_name;
            float temp;
            string shift;
            int capacity, hour, minute;
            DataTable po_plan;
            DataTable line_plan;
            DateTime date;
            TimeSpan from_time_1, to_time_1, from_time_2, to_time_2,from_time_3, to_time_3, start_time, end_time,  from_time, to_time, po_time;
            TimeSpan temp_time;

            DateSelect_Dialog_Form selectDate_Dialog = new DateSelect_Dialog_Form(DateTime.Now);
            if (selectDate_Dialog.ShowDialog() == DialogResult.OK)
            {
                date = selectDate_Dialog.Select_Date;
                // lay du lieu ke hoach sx theo line cua ngay da chon
                sql_cmd = String.Format("SELECT * FROM [JOB_ASSIGNMENT_DB].[dbo].[P_004_KeHoachSanXuatTheoTram] WHERE [Date] = '{0}' order by LineId", date.ToString("yyyy-MM-dd"));
                b = ProductionPlanDetail_MasterDatabase.MasterDatabase_GridviewTBL.Load_DataBase(MasterDatabase_Connection_Str, sql_cmd);
                if (b == false)
                {
                    return;
                }

                count = ProductionPlanDetail_MasterDatabase.MasterDatabase_GridviewTBL.Data_dtb.Rows.Count;
                if (count > 0)
                {
                    mess = "Plan for date:" + date.ToString("dd MMM yyyy") + "was existing\n";
                    mess += "Do you want to delete and create the new one?";

                    if (MessageBox.Show(mess, "Warning", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }
                    DeletePlanforLine(date);
                    ProductionPlanDetail_MasterDatabase.MasterDatabase_GridviewTBL.Load_DataBase(MasterDatabase_Connection_Str, sql_cmd);
                }

                line_plan = Load_KeHoachSX_Theo_Line(date);
                // Load all part in date
                DataTable list_all_part = (Load_KHSX_DB_Date(date)).Copy();
                foreach (DataRow row in list_all_part.Rows)
                {
                    part = row["PartNumber"].ToString().Trim();
                    line_id = row["LineID"].ToString().Trim();
                    line_name = row["LineName"].ToString().Trim();
                    subline = row["SubLine_ID"].ToString().Trim();
                    subline_name = row["SubLine_Name"].ToString().Trim();
                    cell_str = row["Shift_1_From"].ToString().Trim();
                    from_time_1 = row["Shift_1_From"].ToString().Trim() == "" ? TimeSpan.Parse("00:00:00") : (TimeSpan)row["Shift_1_From"];
                    to_time_1 = row["Shift_1_To"].ToString().Trim() == "" ? TimeSpan.Parse("00:00:00") : (TimeSpan)row["Shift_1_To"];
                    from_time_2 = row["Shift_2_From"].ToString().Trim() == "" ? TimeSpan.Parse("00:00:00") : (TimeSpan)row["Shift_2_From"];
                    to_time_2 = row["Shift_2_To"].ToString().Trim() == "" ? TimeSpan.Parse("00:00:00") : (TimeSpan)row["Shift_2_To"];
                    from_time_3 = row["Shift_3_From"].ToString().Trim() == "" ? TimeSpan.Parse("00:00:00") : (TimeSpan)row["Shift_3_From"];
                    to_time_3 = row["Shift_3_To"].ToString().Trim() == "" ? TimeSpan.Parse("00:00:00") : (TimeSpan)row["Shift_3_To"];

                    if (from_time_1 != TimeSpan.Parse("00:00:00"))
                    {
                        shift = SHIFT_1;
                        start_time = from_time_1;
                        end_time = to_time_1;
                    }
                    else if (from_time_2 != TimeSpan.Parse("00:00:00"))
                    {
                        shift = SHIFT_2;
                        start_time = from_time_2;
                        end_time = to_time_2;
                    }
                    else if (from_time_3 != TimeSpan.Parse("00:00:00"))
                    {
                        shift = SHIFT_3;
                        start_time = from_time_3;
                        end_time = to_time_3;
                    }
                    else
                    {
                        mess = "Can't get From Time for Part: " + part;
                        MessageBox.Show(mess, "Error");
                        return;
                    }

                    capacity = (int)row["Capacity"];
                    
                    po_plan =  Load_PO_Plan(date, part);
                    foreach(DataRow po_row in po_plan.Rows )
                    {
                        po = po_row["PO"].ToString().Trim();
                        try
                        {
                            qty = Convert.ToInt32(po_row["Qty"].ToString().Trim());
                            po_time =  Get_PO_RunTime(qty, capacity);
                            from_time = start_time;
                            temp_time = po_time + from_time;
                            if (temp_time.Days >= 1)
                            {
                                temp_time = temp_time - TimeSpan.Parse("23:59:59");
                                temp_time = temp_time - TimeSpan.Parse("00:00:01");
                            }
                            if (temp_time <= end_time)
                            {
                                to_time = from_time + po_time;
                                Create_Detail_Plan_for_PO(date, po, part, line_id, line_name, subline, subline_name, qty, shift, from_time, to_time);
                                start_time = to_time;
                            }
                            else
                            {
                                to_time = end_time;
                                po_time = to_time - from_time;
                                hour = po_time.Hours;
                                minute = po_time.Minutes;
                                temp = hour + minute / 60;
                                temp_qty = (int)(temp * capacity);

                                Create_Detail_Plan_for_PO(date, po, part, line_id, line_name, subline, subline_name, temp_qty, shift, from_time, to_time);

                                switch (shift)
                                { 
                                    case SHIFT_1:
                                        if (from_time_2 != TimeSpan.Parse("00:00:00"))
                                        {
                                            shift = SHIFT_2;
                                            start_time = from_time_2;
                                            end_time = to_time_2;
                                        }
                                        else if (from_time_3 != TimeSpan.Parse("00:00:00"))
                                        {
                                            shift = SHIFT_3;
                                            start_time = from_time_3;
                                            end_time = to_time_3;
                                        }
                                        else
                                        {
                                            mess = "Can't get From Time for Part: " + part;
                                            MessageBox.Show(mess, "Error");
                                            return;
                                        }
                                        break;
                                    case SHIFT_2:
                                        if (from_time_3 != TimeSpan.Parse("00:00:00"))
                                        {
                                            shift = SHIFT_3;
                                            start_time = from_time_3;
                                            end_time = to_time_3;
                                        }
                                        else
                                        {
                                            mess = "Can't get From Time for Part: " + part;
                                            MessageBox.Show(mess, "Error");
                                            return;
                                        }
                                        break;
                                    default:
                                        mess = "Can't get From Time for Part: " + part;
                                        MessageBox.Show(mess, "Error");
                                        return;
                                        break;
                                }
                                qty = qty - temp_qty;
                                Create_Detail_Plan_for_PO(date, po, part, line_id, line_name, subline, subline_name, qty, shift, from_time, to_time);
                            }

                        }
                        catch
                        {
                            qty = 0;
                            from_time = TimeSpan.Parse("00:00:00");
                            to_time = TimeSpan.Parse("00:00:00");
                        }

                        
                    }
                }
            }
        }

        bool Create_Detail_Plan_for_PO(DateTime date, string po, string part, string line_id, string line_name, string subline, string subline_name,
            int qty, string shift, TimeSpan from_time, TimeSpan to_time)
        {
            string wst, wst_name;
            DataTable list_wst = Get_List_wst(part);
            foreach (DataRow wst_row in list_wst.Rows)
            {
                //Create new data for Plan of Line
                wst = wst_row["WST_ID"].ToString();
                wst_name = wst_row["WST_Name"].ToString();
                Create_Update_PlanDetail(date, shift, po, part, line_id, line_name, subline, subline_name, wst, wst_name, qty, from_time, to_time);
            }

            return true;
        }

        TimeSpan Get_PO_RunTime(int qty, int capacity)
        {
            int hour, minute;
            TimeSpan po_time;
            hour = qty * 8 / capacity;
            minute = qty * 8 * 60 / capacity;
            minute = minute % 60;
            po_time = TimeSpan.Parse(hour.ToString() + ":" + minute.ToString() + ":00");
            return po_time;
        }
    }
}